package com.gw.quotes.activity.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.gw.quotes.R;
import com.gw.quotes.activity.PriceInfoActivity;
import com.gw.quotes.activity.PriceListActivity;
import com.gw.quotes.adapter.SearchAdapter;
import com.gw.quotes.adapter.SortAdapter;
import com.gw.quotes.adapter.SortLvAdapter;
import com.gw.quotes.entity.business.Goodsclass;
import com.gw.quotes.entity.business.Priceinfo;
import com.gw.quotes.entity.business.SearchPriceList;
import com.gw.quotes.entity.business.SearchPriceList.PriceList;
import com.gw.quotes.net.BaseServiceInter;
import com.gw.quotes.net.HttpCallBack;
import com.gw.quotes.net.Request;
import com.gw.quotes.net.Response;
import com.gw.quotes.net.service.GoodsClassQueryServiceImpl;
import com.gw.quotes.net.service.GoodsListQueryServiceImpl;
import com.gw.quotes.net.service.PriceListSearchServiceImpl;
import com.gw.quotes.net.service.PriceinfoQueryServiceImpl;
import com.gw.quotes.util.CommonTools;
import com.yxw.util.StringUtils;
import com.yxw.view.NoScrollListView;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;

public class SortFragment extends BaseMainFragment implements IXListViewListener {

	private final int sort_banner[] = {R.drawable.sort_banner_0, R.drawable.sort_banner_1, R.drawable.sort_banner_2, R.drawable.sort_banner_3,
			R.drawable.sort_banner_4, R.drawable.sort_banner_5, R.drawable.sort_banner_6, R.drawable.sort_banner_7, R.drawable.sort_banner_8
			,R.drawable.sort_banner_9,R.drawable.sort_banner_10};
	private String content = "";
	private View contextView = null;
	private ArrayList<Goodsclass> goodsclasslist;
	private ArrayList<Goodsclass> goodsclasslistlv;
	private SearchAdapter searchAdapter;
	private boolean flag = true;

	// 数据
	private SearchPriceList searchPriceList;

	// UI组件
	@ViewInject(id = R.id.sort_listview)
	private YXWXListView sort_listview;
	@ViewInject(id = R.id.search_listview)
	private YXWXListView search_listview;
	@ViewInject(id = R.id.lv_classs1)
	private ListView lv_class1;
	@ViewInject(id = R.id.lv_classs2)
	private NoScrollListView lv_class2;
	@ViewInject(id = R.id.sort_banner_img)
	private ImageView sort_banner_img;
	@ViewInject(id = R.id.search_edit)
	private EditText search_edit;
	@ViewInject(id = R.id.search_button, click = "onSearch")
	private Button search_button;
	// @ViewInject(id = R.id.bg_listview_layout)
	// private LinearLayout bg_listview;
	@ViewInject(id = R.id.lv_listview_layout)
	private LinearLayout lv_listview;
	private int searchPageNo;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (contextView == null) {
			contextView = inflater.inflate(R.layout.fragment_activity_sort, null);
		}
		ViewGroup parent = (ViewGroup) contextView.getParent();
		if (parent != null) {
			parent.removeView(contextView); 
		}
		FinalActivity.initInjectedView(this, contextView);
		initView();
		return contextView;
	}

	@Override
	public void onResume() {
		super.onResume();
		if ((goodsclasslist = (ArrayList<Goodsclass>) aCache.getAsObject("sortlist")) == null) {
			sort_listview.startRefresh();
		} else {
			Date lastdate = aCache.getLastSaveTime("sortlist");
			sort_listview.setRefreshTime(lastdate == null ? "尚未更新" : DateFormat.format("yyyy-MM-dd hh:mm:ss", lastdate).toString());
			setData(goodsclasslist);
		}
	}

	private void initView() {
		sort_listview.setPullRefreshEnable(true);
		sort_listview.setPullLoadEnable(false);
		sort_listview.setXListViewListener(this);

		search_listview.setPullRefreshEnable(true);
		search_listview.setPullLoadEnable(true);
		search_listview.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				searchPageNo = 1;	
				requestSearch(YXWXListView.ACTION_REFRESH);
			}

			@Override
			public void onLoadMore() {
				searchPageNo++;
				requestSearch(YXWXListView.ACTION_LOADMORE);

			}
		});

		search_listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				PriceList priceList = searchPriceList.getPricelist().get(position-1);
				getPriceInfo(priceList.getPriceguid(), priceList.getGoodsname());
			}
		});
		search_edit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String content = s.toString();
				if (content.equals("")) {
					if (flag) {
						sort_listview.setVisibility(View.VISIBLE);
						search_listview.setVisibility(View.GONE);
						lv_listview.setVisibility(View.GONE);
						// bg_listview.setVisibility(View.GONE);
					} else {
						sort_listview.setVisibility(View.GONE);
						search_listview.setVisibility(View.GONE);
						lv_listview.setVisibility(View.VISIBLE);
						// bg_listview.setVisibility(View.VISIBLE);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	private void setData(final ArrayList<Goodsclass> list) {
		flag = true;
		if (flag) {
			sort_listview.setAdapter(new SortAdapter(contextView.getContext(), R.layout.item_sort, list, true, aCache));
			sort_listview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// 当还未家在完成时，不能点击进入
					// if ((goodsclasslistlv = (ArrayList<Goodsclass>) aCache
					// .getAsObject("sortlistlv" + id)) == null) {
					// return;
					// }
					hideInputMode();
					flag = false;
					sort_listview.setVisibility(View.GONE);
					lv_listview.setVisibility(View.VISIBLE);
					// bg_listview.setVisibility(View.VISIBLE);
					lv_class1.setAdapter(new SortAdapter(contextView.getContext(), R.layout.item_sort, list, false, aCache));
					// int bannerRes = R.drawable.banner;

					// 判断是否超出数组
					if (id < sort_banner.length) {
						sort_banner_img.setImageResource(sort_banner[(int) id]);
					} else {
						sort_banner_img.setImageResource(0);
					}

					getgoodsClassListlv(list.get((int) id).getGoodsclassguid(), (int) id);
					lv_class1.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							// 当还未家在完成时，不能点击进入
							// if ((goodsclasslistlv = (ArrayList<Goodsclass>) aCache
							// .getAsObject("sortlistlv" + id)) == null) {
							// return;
							// }
							hideInputMode();
							// int bannerRes = R.drawable.banner;
							if (id < sort_banner.length) {
								sort_banner_img.setImageResource(sort_banner[(int) id]);
							} else {
								sort_banner_img.setImageResource(0);
							}

							getgoodsClassListlv(list.get((int) id).getGoodsclassguid(), (int) id);
						}
					});
				}
			});
			sort_listview.setVisibility(View.VISIBLE);
			lv_listview.setVisibility(View.GONE);
			// bg_listview.setVisibility(View.GONE);
		}
		// lv_class1.setLayoutParams(new LinearLayout.LayoutParams(
		// LinearLayout.LayoutParams.MATCH_PARENT,
		// LinearLayout.LayoutParams.MATCH_PARENT, 4));
		// lv_class2.setLayoutParams(new LinearLayout.LayoutParams(
		// LinearLayout.LayoutParams.MATCH_PARENT,
		// LinearLayout.LayoutParams.MATCH_PARENT, 2));
	}

	// 隐藏软键盘
	private void hideInputMode() {
		((InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity()
				.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void getgoodsClassListlv(String goodsclassguid, int id) {
		if ((goodsclasslistlv = (ArrayList<Goodsclass>) aCache.getAsObject("sortlistlv" + id)) == null) {
			getGoodsClass(goodsclassguid, id);
			lv_class2.setAdapter(new SortLvAdapter(contextView.getContext(), R.layout.item_sort_lv, goodsclasslistlv));
		} else {
			lv_class2.setAdapter(new SortLvAdapter(contextView.getContext(), R.layout.item_sort_lv, goodsclasslistlv));
		}
		lv_class2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(contextView.getContext(), PriceListActivity.class);
				intent.putExtra("goodstitle", goodsclasslistlv.get((int) id).getGoodsclassname());
				intent.putExtra("goodsclassguid", goodsclasslistlv.get((int) id).getGoodsclassguid());
				startActivity(intent);
			}
		});
	}

	private void getGoodsClass(String goodsclassguid, final int id) {
		BaseServiceInter httpService = new GoodsListQueryServiceImpl();
		Request request = new Request();
		request.setGoodsclassguid(goodsclassguid);
		Response response = httpService.handler(request, new HttpCallBack<Response<ArrayList<Goodsclass>>>() {
			@Override
			public void onFinished(Response<ArrayList<Goodsclass>> response) {
				if (response.getResult() == 1) {
					goodsclasslistlv = response.getObj();
				} else {
					Toast.makeText(getActivity(), "请求失败", 1).show();
				}
			}
		});
	}

	private void getGoodsClass() {
		BaseServiceInter httpService = new GoodsClassQueryServiceImpl();
		Request request = new Request();
		Response response = httpService.handler(request, new HttpCallBack<Response<ArrayList<Goodsclass>>>() {
			@Override
			public void onFinished(Response<ArrayList<Goodsclass>> response) {
				if (response.getResult() == 1) {
					if (content.equals("")) {
						goodsclasslist = response.getObj();
						aCache.put("sortlist", goodsclasslist);
						setData(goodsclasslist);
						onLoadFinish();
					}
				} else {
					Toast.makeText(getActivity(), "请求失败", 1).show();
				}
			}
		});
	}

	/**
	 * 发送搜索请求
	 */
	private void requestSearch(final int requestType) {
		Log.i("xd", content);
		// Toast.makeText(contextView.getContext(), content, 1).show();
		if (requestType == YXWXListView.ACTION_REFRESH) {
			content = search_edit.getText().toString();
			
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(content);
			content = m.replaceAll("");
			
			// search_edit.setText(content);// 重置搜索条目
		}
		BaseServiceInter httpService = new PriceListSearchServiceImpl();
		Request request = new Request();
		request.setName(content);
		request.setPageNo(searchPageNo);
		Response response = httpService.handler(request, new HttpCallBack<SearchPriceList>() {
			@Override
			public void onFinished(SearchPriceList response) {
				if (response.getResult() == Response.RESULT_SUCCESS) {
					if (response.getPricelist() != null && response.getPricelist().size() > 0) {
						if (requestType == YXWXListView.ACTION_REFRESH) {
							// 刷新或者第一次加载时的操作
							searchPriceList = response;
							if (response.getPricelist().size() < 10) {
								search_listview.setPullLoadEnable(false);
							} else {
								search_listview.setPullLoadEnable(true);
							}
						} else {
							// 上拉加载更多
							if (response.getPricelist().size() <10) {
								search_listview.setPullLoadEnable(false);
								CommonTools.showShortToast(context, "已是最后一页！");
							}
							CommonTools.MergeArrayList(searchPriceList.getPricelist(), response.getPricelist());
						}
						loadSearchDate(requestType);
						search_listview.setVisibility(View.VISIBLE);
						sort_listview.setVisibility(View.GONE);
						lv_listview.setVisibility(View.GONE);
					} else {
						// 数据请求失败或者没有数据
						search_listview.setVisibility(View.GONE);
						sort_listview.setVisibility(View.VISIBLE);
						lv_listview.setVisibility(View.GONE);
						CommonTools.showShortToast(context, "没有查到数据！");
					}
				} else {
					CommonTools.showShortToast(context, "请求失败！");
				}
				onSearchLoadFinish();
				dialog.dismiss();
			}
		});
	}

	/**
	 * onClick 搜索按钮
	 * 
	 * @param v
	 */
	public void onSearch(View v) {
		searchPageNo = 1;
		hideInputMode();
		if (StringUtils.isEmpty(search_edit.getText().toString())) {
			Toast.makeText(contextView.getContext(), "请输入搜索内容", Toast.LENGTH_SHORT).show();
		} else {
			dialog.show();
			requestSearch(YXWXListView.ACTION_REFRESH);
		}
	}

	/**
	 * 加载数据查询列表
	 */
	private void loadSearchDate(int type) {
		// ...............加载数据...............
		if (searchAdapter == null || type == YXWXListView.ACTION_REFRESH) {
			searchAdapter = new SearchAdapter(contextView.getContext(), R.layout.item_search, searchPriceList.getPricelist());
			search_listview.setAdapter(searchAdapter);
		} else {
			searchAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 得到商品信息 并传递到商品详细页面
	 * 
	 * @param priceguid
	 * @param goodsname
	 */
	private void getPriceInfo(final String priceguid, final String goodsname) {
		dialog.show();
		BaseServiceInter httpService = new PriceinfoQueryServiceImpl();
		Request request = new Request();
		request.setPriceguid(priceguid);
		Response response = httpService.handler(request, new HttpCallBack<Response<Priceinfo>>() {
			@Override
			public void onFinished(Response<Priceinfo> response) {
				dialog.dismiss();
				if (response.getResult() == 1) {
					// CommonTools.showShortToast(getActivity(),
					// "msg:" + response.getMsg() + "result:"
					// + response.getResult());
					Intent intent = new Intent(getActivity(), PriceInfoActivity.class);
					intent.putExtra("title", goodsname);
					intent.putExtra("priceinfo", response.getObj());
					startActivity(intent);
				} else {
					Toast.makeText(getActivity(), "请求失败", 1).show();
				}
			}
		});
	}

	/**
	 * 查找页面加载结束时调用
	 */
	private void onSearchLoadFinish() {
		search_listview.stopRefresh();
		search_listview.stopLoadMore();
		// 设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		search_listview.setRefreshTime(df.format(new Date()));
	}

	/**
	 * 分类页面加载结束时调用
	 */
	private void onLoadFinish() {
		sort_listview.stopRefresh();
		sort_listview.stopLoadMore();
		// 设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sort_listview.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		getGoodsClass();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	/**
	 * 返回键监听，依赖Activity
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (search_listview.getVisibility() == View.VISIBLE) {
			search_edit.setText("");
			return false;
		}
		if (lv_listview.getVisibility() == View.VISIBLE) {
			sort_listview.setVisibility(View.VISIBLE);
			search_listview.setVisibility(View.GONE);
			lv_listview.setVisibility(View.GONE);
			// bg_listview.setVisibility(View.GONE);
			return false;
		}
		return super.dispatchKeyEvent(event);
	}

}
